package com.cykj.page04;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page04
 * @Author: WWJ
 * @CreateTime: 2025-06-15 00:07
 * @Description:  动态获取静态资源
 * @Version: 1.0
 */
public class MySever {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9090);
        System.out.println("服务器启动成功，监听端口：9090");
        Socket socket = serverSocket.accept();
        while (true){
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = inputStream.read(bytes);
            String request = new String(bytes, 0, len);
            System.out.println("客户端请求数据：\n" + request);
            MyHttpRequest httpRequest = new MyHttpRequest(request);
            String filePath ="webapps"+httpRequest.getRequestURL();
            File file = new File(filePath);
            if (httpRequest.getRequestURL().equals("/")){
                filePath = "webapps/pages/index.html";
            }else if (!file.exists()){
                filePath = "webapps/pages/404.html";
            }
            StaticResourceHandler staticResourceHandler = new StaticResourceHandler(filePath);
            //响应
            MyHttpResponse myHttpResponse = new MyHttpResponse(socket);
            //静态资源处理器获取文件的媒体类型和字节数据
            myHttpResponse.write(staticResourceHandler.getMedia(),staticResourceHandler.getFileBytes());
        }

    }
}
